<template>
  <el-input
    v-model="vValue"
    show-word-limit
    v-bind="attrs"
    :autosize="attrs.rows ? false : { minRows: 4 }"
    :disabled="disabled"
    clearable
    resize="none"
    :class="`${attrs.class} ${className}`"
    @blur="handleBlur"
    @focus="itemEvent('focus', $event)"
    @input="itemEvent('input', $event)"
    @change="itemEvent('change', $event)"
    @clear="itemEvent('clear', $event)"
    @keyup.enter.native="itemEvent('keyupEnter', $event)"
  >
    <template v-if="prependSlot" #prepend>
      <slot name="prepend" :config="{ ...attrs, prependSlot: prependSlot }">{{ prependSlot }}</slot>
    </template>

    <template v-if="appendSlot" #append>
      <slot name="append" :config="{ ...attrs, appendSlot: appendSlot }">{{ appendSlot }}</slot>
    </template>
  </el-input>
</template>
<script setup>
import _ from 'lodash';
const attrs = useAttrs();
import { vModelValue } from '@/utils/hooks.js';

const props = defineProps({
  modelValue: {
    type: [Number, String],
    default: '',
  },
  prependSlot: {
    // prepend 插槽名
    type: String,
    default: '',
  },
  appendSlot: {
    // append 插槽名
    type: String,
    default: '',
  },
});
const emits = defineEmits(['update:modelValue', 'itemEvent']);
const { newValue: key } = vModelValue(props, emits);
let vValue = ref(key);

// 是否禁用
const disabled = computed(() => {
  return attrs.disabledFn && _.isFunction(attrs.disabledFn)
    ? attrs.disabledFn({ ...props, ...attrs })
    : attrs.disabled || false;
});

const className = computed(() => {
  let str = '';
  const { itemClass, classFormat, row } = attrs;
  if (itemClass) str += itemClass;
  if (classFormat && _.isFunction(classFormat)) {
    str += classFormat(row);
  }
  return str;
});

// 失去焦点，清除左右空格
function handleBlur() {
  vValue.value = vValue.value?.trim();
  itemEvent('blur', vValue.value);
}

// input事件传给父组件
function itemEvent(eventName, $event) {
  emits('itemEvent', {
    eventName, // 事件名
    prop: attrs.prop,
    value: $event,
  });
}
</script>
<style lang="scss" scoped>
.form_item_error {
  :deep() {
    .el-input__wrapper {
      box-shadow: 0 0 0 1px var(--el-color-danger) inset;
    }
  }
}
</style>
